/*
 * @lc app=leetcode.cn id=71 lang=cpp
 *
 * [71] 简化路径
 */
#include <iostream>
#include <stack>
#include <string>

using namespace std;
// @lc code=start
class Solution
{
  public:
    string simplifyPath(string path)
    {
        stack<char> new_path;
        stack<char> result;
        string result_str;

        new_path.push('/');
        auto it_path = path.cbegin();
        auto path_end = path.cend();
        for (; it_path != path_end; ++it_path) {
            if (new_path.top() == '/' && *it_path == '/') {
                continue;
            } else if (*it_path == '.') {
                int dot_num = 1;
                auto pre_it_path = it_path - 1;
                while (it_path + 1 != path_end && *(it_path + 1) == '.') {
                    ++dot_num;
                    ++it_path;
                }

                if (it_path + 1 != path_end && *(it_path + 1) != '/' ||
                    pre_it_path != path.cbegin() && *pre_it_path != '/' ||
                    dot_num > 2) {
                    while (dot_num--) {
                        new_path.push('.');
                    }
                    continue;
                }

                if (dot_num == 1) {
                    continue;
                } else {
                    if (new_path.size() > 1 && new_path.top() == '/') {
                        new_path.pop();
                    }
                    while (new_path.top() != '/') {
                        new_path.pop();
                    }
                }
            } else {
                new_path.push(*it_path);
            }
        }

        if (new_path.size() > 1 && new_path.top() == '/') {
            new_path.pop();
        }

        while (!new_path.empty()) {
            result.push(new_path.top());
            new_path.pop();
        }

        while (!result.empty()) {
            result_str.push_back(result.top());
            result.pop();
        }

        return result_str;
    }
};
// @lc code=end

int main()
{
    Solution s;
    string path = "/hello../world";
    string result = s.simplifyPath(path);
    cout << result << endl;
    return 0;
}
